const mongoose = require('mongoose')
const handleE11000 = require('../common/error-handle.api').handleE11000
const Counter = require('../model/counter.model')
const AnnouncementTag = require('../model/announcement-tag.model')
const ManagementTag = require('../model/management-tag.model')
const Schema = mongoose.Schema
const TeamSchemaConfig = {
  versionKey: false,
  timestamps: {
    createdAt: 'created_at',
    updatedAt: false
  }
}

const TeamSchema = new Schema({
  name: { type: String, required: true },
  allow_join: { type: Boolean, default: false },
  years: { type: Number, max: 5, min: 3, default: 4 },
  team_code: { type: String, unique: true },
  classes: [String],
  management_tags: [{ type: Schema.Types.ObjectId, ref: 'ManagementTag' }],
  members: [{ type: Schema.Types.ObjectId, ref: 'User' }],
  dormitories: [{
    name: String,
    rooms: [{
      room: String,
      star: { type: Boolean, default: false }
    }]
  }],
  announcement_tags: [{ type: Schema.Types.ObjectId, ref: 'AnnouncementTag' }],
  evaluations: [{ type: Schema.Types.ObjectId, ref: 'Evaluation' }],
  scholarships: [{ type: Schema.Types.ObjectId, ref: 'Scholarship' }],
  contrasts: [{ type: Schema.Types.ObjectId, ref: 'Contrast' }]
}, TeamSchemaConfig)

// middleware
// 根据当前团队数目计算team_code
TeamSchema.pre('save', function(next) {
  const teamDoc = this
  Counter.findByIdAndUpdate('teamId', { $inc: { seq: 1 }}, function(err, counter) {
    if (err) return next(err)
    teamDoc.team_code = counter.seq + 10000
    next()
  })
})

// 默认七类通知类型
TeamSchema.pre('save', function(next) {
  const teamDoc = this
  const defaultAnnouncementTagNames = ['就业招聘', '实习招聘', '考勤公示', '党务通知', '学生工作通知公示', '教学工作通知公示', '创新创业通知公示']
  for (let i = 0; i < defaultAnnouncementTagNames.length; i++) {
    const tag = new AnnouncementTag({ name: defaultAnnouncementTagNames[i] })
    tag.save()
    teamDoc.announcement_tags.push(tag.id)
  }
  next()
})

// 默认三类学生标签
TeamSchema.pre('save', function(next) {
  const teamDoc = this
  const defaultManagementTag = [
    { name: '班级学生干部', announcement: true },
    { name: '评优小组', evaluation: true },
    { name: '党团小组', party: true }
  ]
  for (let i = 0; i < defaultManagementTag.length; i++) {
    const tag = new ManagementTag(defaultManagementTag[i])
    tag.save()
    teamDoc.management_tags.push(tag.id)
  }
  next()
})

TeamSchema.post('save', handleE11000)
TeamSchema.post('update', handleE11000)
TeamSchema.post('findOneAndUpdate', handleE11000)
TeamSchema.post('insertMany', handleE11000)

exports = module.exports = TeamSchema
